package com.bgy.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.qyweixin.sdk.api.ApiConfig;
import com.jfinal.qyweixin.sdk.api.ApiConfigKit;
import com.jfinal.qyweixin.sdk.api.ApiResult;
import com.jfinal.qyweixin.sdk.api.JsTicket;
import com.jfinal.qyweixin.sdk.api.JsTicketApi;
import com.jfinal.qyweixin.sdk.api.JsTicketApi.JsApiType;
import com.jfinal.qyweixin.sdk.api.OAuthApi;
import com.jfinal.qyweixin.sdk.jfinal.ApiController;


/**
 * 控制前端js调用，会议列表使用，为了实现企业会话功能
 * @author Administrator
 *
 */
public class QyMeetingDetailController extends ApiController {
	
	private Logger logger=Logger. getLogger(QyMeetingDetailController.class);
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setCorpId(PropKit.get("corpId"));
		ac.setCorpSecret(PropKit.get("secret"));						
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
	
	/**
	 * jsapi 验证属性，其它验证属性
	 */
	private void setJsApiAttr(String nonce_str,String timestamp,String url) {
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		String jsapi_ticket = jsApiTicket.getTicket();							
		String[] paramArr = new String[] {"jsapi_ticket=" + jsapi_ticket, "noncestr=" + nonce_str, "timestamp=" + timestamp,"url=" + url };  
        Arrays.sort(paramArr); //将排序后的结果拼接成一个字符串           
        String content = paramArr[0].concat("&"+paramArr[1]).concat("&"+paramArr[2]).concat("&"+paramArr[3]);  
		String signature = HashKit.sha1(content);		
		setAttr("appId", ApiConfigKit.getApiConfig().getCorpId());
		setAttr("nonceStr", nonce_str);
		setAttr("timestamp", timestamp);
		setAttr("url", url);
		setAttr("signature", signature);
		setAttr("jsapi_ticket", jsapi_ticket);		
	}	
		
	public void code(){
		if (isParaBlank("code")) {
			renderJsp("meeting_detail.jsp");
			return;
		}
		String userId = null;
		String code = getPara("code");			
		ApiResult userInfoApiResult = OAuthApi.getUserInfoByCode(code);
		if (userInfoApiResult.isSucceed()) {
			String userInfoJson=userInfoApiResult.getJson();
			JSONObject object = JSON.parseObject(userInfoJson);
			userId = object.getString("UserId"); //如果获取userId为空 说明没有关注
		}						
		setAttr("openID", userId);
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();	 //注意这里参数名必须全部小写，且必须有序 		
		String url = "http://" + getRequest().getServerName() + getRequest().getContextPath() + getRequest().getServletPath();
		String qs = getRequest().getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (getRequest().getQueryString());
		}
		logger.info(url);					
		String xh = getPara("xh"); //获取状态信息
		setAttr("xh", xh);		
		setJsApiAttr(nonce_str,timestamp,url);
		renderJsp("meeting_detail.jsp");			
	}	
	
	public void index(){
		String xh = getPara("xh"); //获取状态信息
		String url = "http://" + getRequest().getServerName() + getRequest().getContextPath() + getRequest().getServletPath();
		System.out.println("我的url是:" + url);
		try {
			String redirect_uri=URLEncoder.encode(url + "/code?xh=" + xh, "utf-8");
			String codeUrl = OAuthApi.getCodeUrl(redirect_uri, "123");
			redirect(codeUrl);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}	
	
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}	
}
